package com.ycsj.goldmedalnewconcept.activity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.utils.BitmapCompressor;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.R;

//上传视频
public class UploadVideoActivity extends Activity implements OnClickListener {

	private ImageView iv_back;
	private LinearLayout ll_shaike;
	private LinearLayout ll_pingke;
	private TextView tv_shaike;
	private TextView tv_pingke;
	private ImageView iv_upload_photo;
	private TextView tv_submit;
	private EditText et_videoname;
	private EditText et_videourl;
	private String vtype;
	private String ImgPath;
	private PopupWindow mPopWindow;
	protected static final int CHOOSE_PICTURE = 0;
	protected static final int TAKE_PICTURE = 1;
	private static final int CROP_SMALL_PICTURE = 2;
	protected static Uri tempUri;
	private int mWH = 360;
	private HttpUtils httpUtils;
	private String url;
	private String videourl;
	private RequestParams params;
	private String account;
	private String role;
	private String title;
	private String tag;
	private File f;
	private String schoolId;
	
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_uploadvideo);
		vtype = "0";
		account = SPUtil.getString(this, "account", "");
		role = SPUtil.getString(this, "role", "");
		schoolId = SPUtil.getString(this, "schoolId", "");
		initView();
		setOnListener();
		initData();
	}

	private void initView() {
		// TODO Auto-generated method stub
		iv_back = (ImageView) findViewById(R.id.iv_back);
		ll_shaike = (LinearLayout) findViewById(R.id.ll_shaike);
		ll_pingke = (LinearLayout) findViewById(R.id.ll_pingke);
		tv_shaike = (TextView) findViewById(R.id.tv_shaike);
		tv_pingke = (TextView) findViewById(R.id.tv_pingke);
		iv_upload_photo = (ImageView) findViewById(R.id.iv_upload_photo);
		tv_submit = (TextView) findViewById(R.id.tv_submit);
		et_videoname = (EditText) findViewById(R.id.et_videoname);
		et_videourl = (EditText) findViewById(R.id.et_videourl);

	}

	private void initData() {
		// TODO Auto-generated method stub

	}

	private void setOnListener() {
		// TODO Auto-generated method stub
		iv_back.setOnClickListener(this);
		ll_shaike.setOnClickListener(this);
		ll_pingke.setOnClickListener(this);
		iv_upload_photo.setOnClickListener(this);
		tv_submit.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.iv_back:
			finish();
			break;
		case R.id.ll_shaike:
			vtype = "0";
			tv_pingke.setBackground(this.getResources().getDrawable(
					R.drawable.weixuan));
			tv_shaike.setBackground(this.getResources().getDrawable(
					R.drawable.yixuan));
			break;
		case R.id.ll_pingke:
			vtype = "1";
			tv_shaike.setBackground(this.getResources().getDrawable(
					R.drawable.weixuan));
			tv_pingke.setBackground(this.getResources().getDrawable(
					R.drawable.yixuan));
			break;
		case R.id.iv_upload_photo:
			InputMethodManager imm3 = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			if (imm3 != null) {
				imm3.hideSoftInputFromWindow(getWindow().getDecorView()
						.getWindowToken(), 0);
			}
			Popwindow();
			break;
		case R.id.tv_submit:
			submit();
			Log.e("test", "submit");
			break;
		case R.id.tv_pic:  //相册
			
			Intent openAlbumIntent = new Intent(
					Intent.ACTION_GET_CONTENT);
			openAlbumIntent.setType("image/*");
			// Data = Uri.fromFile(new File(Environment
			// .getExternalStorageDirectory(), "image1.jpg"));
			startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
			mPopWindow.dismiss();
			break;
		case R.id.tv_photo://拍照
			Intent openCameraIntent = new Intent(
					MediaStore.ACTION_IMAGE_CAPTURE);
			tempUri = Uri.fromFile(new File(Environment
					.getExternalStorageDirectory(), "image.jpg"));
			openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
			startActivityForResult(openCameraIntent, TAKE_PICTURE);
			mPopWindow.dismiss();
			break;
		case R.id.tv_cancel:
		case R.id.rl_dismiss:
			mPopWindow.dismiss();
			break;
		}
	}

	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) { 
			switch (requestCode) {
			case TAKE_PICTURE:
				startPhotoZoom(tempUri); 
				break;
			case CHOOSE_PICTURE:
				Uri uri = data.getData();
				Bitmap bitmap = null;
				String imgPath = null;
				ContentResolver resolver = this.getContentResolver();
				String[] columns = { MediaStore.Images.Media.DATA };
				Cursor cursor = null;
				cursor = resolver.query(uri, columns, null, null, null);
				imgPath = uri.getPath();
				if (!TextUtils.isEmpty(imgPath) && imgPath.contains(":")) {
					String imgIndex = imgPath.split(":")[1];
					cursor = resolver.query(
							MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
							columns, "_id=?", new String[] { imgIndex }, null);
				}
				if (null != cursor && cursor.moveToFirst()) {
					int columnIndex = cursor.getColumnIndex(columns[0]);
					imgPath = cursor.getString(columnIndex);
					cursor.close();
				}
				if (!TextUtils.isEmpty(imgPath)) {
					bitmap = genBitmap(imgPath);
					iv_upload_photo.setImageBitmap(bitmap);
					}
				
				
				break;
			case CROP_SMALL_PICTURE:
				if (data != null) {
					setImageToView(data);
				}
				break;
			}
		}
	}
	
	
	
	
	protected void setImageToView(Intent data) {
		Bundle extras = data.getExtras();
		if (extras != null) {
			Bitmap photo = extras.getParcelable("data");
			iv_upload_photo.setImageBitmap(photo);
			ImgPath = savePhoto(photo, Environment
					.getExternalStorageDirectory().getAbsolutePath(), String
					.valueOf(System.currentTimeMillis()));
		}
	}
	
	public String savePhoto(Bitmap photoBitmap, String path,
			String photoName) {
		String localPath = null;
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}

			File photoFile = new File(path, photoName + ".png");
			FileOutputStream fileOutputStream = null;
			try {
				fileOutputStream = new FileOutputStream(photoFile);
				if (photoBitmap != null) {
					if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100,
							fileOutputStream)) { 
						localPath = photoFile.getPath();
						fileOutputStream.flush();
					}
				}
			} catch (FileNotFoundException e) {
				photoFile.delete();
				localPath = null;
				e.printStackTrace();
			} catch (IOException e) {
				photoFile.delete();
				localPath = null;
				e.printStackTrace();
			} finally {
				try {
					if (fileOutputStream != null) {
						fileOutputStream.close();
						fileOutputStream = null;
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return localPath;
	}
	
	private Bitmap genBitmap(String imgPath) {
		Options options = new Options();
		// options.inJustDecodeBounds = true;

		// 将图片像素设置为低像素
		options.inDensity = DisplayMetrics.DENSITY_LOW;
		// 降低图片质量 设置为16位
		options.inPreferredConfig = Config.RGB_565;

		BitmapFactory.decodeFile(imgPath, options);
		int imageWidth = options.outWidth;
		int imageHeight = options.outHeight;

		int widthSample = (int) (imageWidth / mWH);
		int heightSample = (int) (imageHeight / mWH);
		if (imageWidth < 2048 || imageHeight < 2048) {
			options.inSampleSize = 1;
		} else if (imageWidth > 2048 || imageHeight > 2048) {
			options.inSampleSize = 4;
		}
		Bitmap bitmap = BitmapFactory.decodeFile(imgPath, options);
		bitmap = BitmapCompressor.decodeSampledBitmapFromBitmap(bitmap,
				imageWidth / (options.inSampleSize * 5), imageHeight
						/ (options.inSampleSize * 5));

		ImgPath = savePhoto(bitmap, Environment
				.getExternalStorageDirectory().getAbsolutePath(), String
				.valueOf(System.currentTimeMillis()));
		return bitmap;
	}
	
	
	public String getSDPath() {
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
		} else {
			sdDir = getFilesDir();
		}
		return sdDir.toString();
	}
	
	protected void startPhotoZoom(Uri uri) {
		if (uri == null) {
			Log.i("tag", "The uri is not exist.");
		}
		tempUri = uri;
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 150);
		intent.putExtra("outputY", 150);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, CROP_SMALL_PICTURE);
	}
	
	private void Popwindow() {

		View contentView = LayoutInflater.from(this).inflate(
				R.layout.popup_uploadphoto, null);
		mPopWindow = new PopupWindow(contentView,
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT, true);
		mPopWindow.setContentView(contentView);
		
		// 设置各个控件的点击响应
		TextView tv_pic = (TextView) contentView.findViewById(R.id.tv_pic);
		TextView tv_photo = (TextView) contentView.findViewById(R.id.tv_photo);
		TextView tv_cancel = (TextView) contentView.findViewById(R.id.tv_cancel);
		RelativeLayout rl_dismiss = (RelativeLayout) contentView.findViewById(R.id.rl_dismiss);
		tv_pic.setOnClickListener(this);
		tv_photo.setOnClickListener(this);
		tv_cancel.setOnClickListener(this);
		rl_dismiss.setOnClickListener(this);

		mPopWindow.setBackgroundDrawable(new BitmapDrawable());
		mPopWindow.setOutsideTouchable(true);
		View rootview = LayoutInflater.from(this).inflate(R.layout.activity_uploadvideo, null);  
        mPopWindow.showAtLocation(rootview,Gravity.BOTTOM, 0, 0);  
	}

	private void submit() {
		
		title = et_videoname.getText().toString().trim();
		videourl = et_videourl.getText().toString();

		if ("".equals(title)) {
			Toast.makeText(this, "请输入视频名称", Toast.LENGTH_SHORT)
					.show();
			return;
		}
		
		if ("".equals(videourl)) {
			Toast.makeText(this, "请输入视频链接", Toast.LENGTH_SHORT)
					.show();
			return;
		}
		
		httpUtils = new HttpUtils();
		url = Constant.SERVER_LOC + "ManageMsg";
		params = new RequestParams();
		params.addBodyParameter("type","23");
		params.addBodyParameter("c", account);
		params.addBodyParameter("role",role);
		params.addBodyParameter("schoolid", schoolId);
		params.addBodyParameter("vtype", vtype);
		params.addBodyParameter("title",title);
		params.addBodyParameter("tag", "");
		params.addBodyParameter("url", videourl);
		params.addBodyParameter("status","0");
		//http://192.168.0.198:8888/ycsj_platform/ManageMsg?type=23&c=18271261779&role=2&teacherid=18271261779&vtype=0
		
		
		
		if(ImgPath!=null){
			f = new File(ImgPath);
			String[] split = ImgPath.split("\\/");
			String name = split[split.length - 1];
			params.addBodyParameter("picname", name);
			params.addBodyParameter(name, f, "image/png");
		}
		
		 httpUtils.send(HttpMethod.POST, url, params,
		 callBackHeadimg);
	}
	
	private RequestCallBack<String> callBackHeadimg = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {

			String json = responseInfo.result;
			Log.e("test", json);
			
			Toast.makeText(getBaseContext(), "上传成功！", 0).show();
			finish();
		}

		@Override
		public void onFailure(HttpException error, String msg) {
			Toast.makeText(getBaseContext(), "上传失败，请重新上传", 0).show();
		}
	};
}










